package com.example.xiaomiao.Service.Impl;

import cn.hutool.json.JSONUtil;
import com.example.xiaomiao.DO.User;
import com.example.xiaomiao.DTO.LoginRequestDTO;
import com.example.xiaomiao.DTO.LoginResponseDTO;
import com.example.xiaomiao.DTO.RegisterRequestDTO;
import com.example.xiaomiao.DTO.Return;
import com.example.xiaomiao.Mapper.UserMapper;
import com.example.xiaomiao.Service.PublicService;
import com.example.xiaomiao.Util.CacheDataBaseUtil;
import com.example.xiaomiao.Util.JwtUtil;
import com.example.xiaomiao.Util.RegexUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.example.xiaomiao.Util.MyConstants.*;

@Service
public class PublicServiceImpl implements PublicService {
    @Resource
    UserMapper userMapper;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    CacheDataBaseUtil cacheDataBaseUtil;
    private static final Logger logger = LoggerFactory.getLogger(PublicServiceImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Return register(RegisterRequestDTO registerRequestData) {
        String telephone = registerRequestData.getTelephone();
        // 检查手机号
        if(RegexUtils.isPhoneInvalid(telephone)){
            return Return.fail(2,"无效的手机号");
        }
        try {
            return register1(telephone,registerRequestData);
        } catch (Exception e){
            return Return.fail(1,"注册失败");
        }
    }

    @Override
    public Return login(LoginRequestDTO loginRequestData) {
        String telephone = loginRequestData.getTelephone();
        String password = loginRequestData.getPassword();
        // 检查手机号
        if(RegexUtils.isPhoneInvalid(telephone)){
            return Return.fail(2,"无效的手机号");
        }
        User user = cacheDataBaseUtil.selectById(USER_KEY,telephone,User.class, telephone2 -> userMapper.getUser(telephone2),USER_CACHE_TTL, TimeUnit.HOURS);
        if(user == null){
            return Return.fail(3,"未注册的用户");
        }
        if(!password.equals(user.getPassword())){
            return Return.fail(1,"密码错误");
        }
        String id = PROJECT_NAME + user.getUser_id();
        // 生成token
        String token = JwtUtil.generateToken(id);
        // 将token和用户绑定，防止重复登录
        stringRedisTemplate.opsForValue().set(TOKEN_KEY+id,token,TOKEN_CACHE_TTL,TimeUnit.HOURS);
        LoginResponseDTO loginReturn = new LoginResponseDTO(token);
        return Return.ok(loginReturn);
    }

    @Transactional(rollbackFor = Exception.class)
    public Return register1(String telephone, RegisterRequestDTO registerRequestData) {
        if(!cacheDataBaseUtil.isContainsById(USER_KEY,telephone, telephone2 -> userMapper.getUser(telephone2),USER_CACHE_TTL, TimeUnit.HOURS)){
            try {
                User new_user = new User(telephone, registerRequestData.getPassword(), registerRequestData.getNickname());
                cacheDataBaseUtil.insert(USER_KEY, telephone, new_user, new_user2 -> userMapper.addUser(new_user2), USER_CACHE_TTL, TimeUnit.HOURS);
                stringRedisTemplate.opsForValue().set(USER_KEY+new_user.getUser_id(), JSONUtil.toJsonStr(new_user),USER_CACHE_TTL, TimeUnit.HOURS);
                return Return.ok();
            } catch (Exception e){
                logger.error(e.getMessage());
                throw new RuntimeException(e);
            }
        }
        return Return.fail(3,"请勿重复注册");
    }
}
